package org.scc.action;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.scc.model.ArticleType;
import org.scc.service.ArticleTypeService;

public class ArticleTypeAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private ArticleTypeService articleTypeService;
	private ArticleType articleType;
	private int ct;
	
	public ArticleTypeAction(){
		articleTypeService = new ArticleTypeService();
	}
	
	public void listArticleTypes(){
		List<ArticleType> articleTypes = articleTypeService.findAll();
		responeString(getArticleTypeJson(articleTypes));
	}
	
	private String getArticleTypeJson(List<ArticleType> articleTypes){
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		for(ArticleType at : articleTypes){
			obj = new JSONObject();
			obj.put("id", at.getId() );
			obj.put("name", at.getName() );
			obj.put("sort", at.getSort() );
			obj.put("showIndex", at.showIndexText() );
			arr.add(obj);
		}
		return arr.toString();
	}
	
	public void initArticleTypeCombo(){
		List<ArticleType> articleTypes = articleTypeService.findAll();
		responeString(getAtComboJson(articleTypes));
	}
	
	private String getAtComboJson(List<ArticleType> articleTypes){
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		obj = new JSONObject();
		if(ct == -1){
			obj.put("value", "-1");
			obj.put("text", "请选择");
			obj.put("selected", "true");
		} else {
			obj.put("value", "0");
			obj.put("text", "全部");
			obj.put("selected", "true");
		}
		arr.add(obj);
		for(ArticleType at : articleTypes){
			obj = new JSONObject();
			obj.put("value", at.getId() );
			obj.put("text", at.getName() );
			arr.add(obj);
		}
		return arr.toString();
	}
	
	public String initEditPage(){
		if(id != 0){
			articleType = articleTypeService.load(id);
		}
		return SUCCESS;
	}

	public void editArticleType(){
		if(articleType.getId() == 0){
			articleTypeService.add(articleType);
		} else {
			articleTypeService.update(articleType);
		}
		responseSuccess();
	}
	
	public void deleteArticleType(){
		articleTypeService.delete(ids);
		responseSuccess();
	}
	
	public void getIndexArticleType(){
		List<ArticleType> articleTypes = articleTypeService.findIndexShow();
		JSONArray arr = new JSONArray();
		JSONObject obj = null;
		for(ArticleType at : articleTypes){
			obj = new JSONObject();
			obj.put("id", at.getId());
			obj.put("name", at.getName());
			
			arr.add(obj);
		}
		responeString(arr.toString() );
	}

	public ArticleType getArticleType() {
		return articleType;
	}

	public void setArticleType(ArticleType articleType) {
		this.articleType = articleType;
	}

	public int getCt() {
		return ct;
	}

	public void setCt(int ct) {
		this.ct = ct;
	}

}
